package com.wst.system.security.provider;


import com.alibaba.fastjson2.JSONObject;
import com.wst.system.config.SecretKeyComponent;
import com.wst.system.config.cache.SysCache;
import com.wst.system.config.cache.SysCacheServer;
import com.wst.system.config.exception.GlobalExcetion;
import com.wst.system.security.SelfUserDetailsService;
import com.wst.system.security.entity.SelfUserEntity;
import com.wst.system.security.entity.SysRoleEntity;
import com.wst.system.security.entity.SysUserEntity;
import com.wst.system.security.exception.AuthCustomException;
import com.wst.system.server.service.SysUserService;
import com.wst.system.util.CryptoContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.parameters.P;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义登录验证
 * @author Xiongx
 * @version 1.0
 * @date 2021/6/11 15:15
 * @since JDK 1.8
 */
@Slf4j
@Component
public class UserAuthenticationProvider implements AuthenticationProvider {

    private final SelfUserDetailsService userDetailsService;

    private final HttpServletRequest request;

    public UserAuthenticationProvider(SelfUserDetailsService userDetailsService, HttpServletRequest request) {
        this.userDetailsService = userDetailsService;
        this.request = request;
    }


    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SecretKeyComponent secretKeyComponent;

    @Autowired
    private SysCacheServer sysCacheServer;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取表单输入中返回的用户名
      //  String userName = (String) authentication.getPrincipal();
        // 获取表单中输入的密码
        //String password = (String) authentication.getCredentials();
        String sessionId=(String)request.getParameter("sessionId");
        String code=null;
        String userName=null;
        String password=null;
        String captchaSid=null;
        log.info("会话id {}",sessionId);
        if(sessionId==null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        String key= secretKeyComponent.getSecretKey(sessionId);
        if(key==null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        String loginStr=request.getParameter("loginStr");
        System.out.println("key: "+key);
        System.out.println("str: "+loginStr);
        loginStr=CryptoContextUtils.decryptAES(loginStr,key);
        try {
            log.info("loginStr:{}",loginStr);
            JSONObject jsonObject=JSONObject.parseObject(loginStr);
            userName=jsonObject.getString("username");
            password=jsonObject.getString("password");
            code=jsonObject.getString("code");
            captchaSid=jsonObject.getString("captchaSid");
            password=CryptoContextUtils.decryptAES(password,key);
            userName=CryptoContextUtils.decryptAES(userName,key);
            code=CryptoContextUtils.decryptAES(code,key);
        }catch (Exception e){
            log.error(e.getMessage());
            throw new BadCredentialsException("密码不正确");
        }
        SysCache sysCache=sysCacheServer.getOnce(captchaSid);
        if(code==null){
            throw new AuthCustomException("验证码未填写");
        }
        if(sysCache==null){
            throw new AuthCustomException("验证码已过期,请刷新系统后重试");
        }
        if(!sysCache.getValue().toString().toLowerCase().equals(code.toLowerCase())){
            System.out.println(sysCache.getValue().toString());
            System.out.println(code.toLowerCase());
            throw new AuthCustomException("验证码不正确");
        }
        if(password==null){
            throw new BadCredentialsException("密码不正确");
        }
        // 查询用户是否存在
        SelfUserEntity userInfo = userDetailsService.loadUserByUsername(userName);
        System.out.println("userInfo:"+ JSONObject.toJSONString(userInfo));
        if (userInfo == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 还可以加一些其他信息的判断，比如用户账号已停用等判断
        if (userInfo.getStatus().equals("PROHIBIT")){
            throw new LockedException("该用户已被冻结");
        }
        SysUserEntity sysUserEntity=sysUserService.getById(userInfo.getUserId());
        // 我们还要判断密码是否正确，这里我们的密码使用BCryptPasswordEncoder进行加密的
        if (!new BCryptPasswordEncoder().matches(password, userInfo.getPassword())) {
            if(sysUserEntity.getLoginFailNum()==null){
                sysUserEntity.setLoginFailNum(0);
            }else {
                sysUserEntity.setLoginFailNum(sysUserEntity.getLoginFailNum()+1);
            }
            if(sysUserEntity.getLoginFailNum()>5){
                //锁定用户
                sysUserEntity.setStatus("PROHIBIT");
            }
            sysUserEntity.setLoginFailDate(new Date());
            sysUserService.updateById(sysUserEntity);
            throw new BadCredentialsException("密码不正确");
        }
        // 角色集合
        Set<GrantedAuthority> authorities = new HashSet<>();
        // 查询用户角色
        List<SysRoleEntity> sysRoleEntityList = sysUserService.selectSysRoleByUserId(userInfo.getUserId());
        if(sysRoleEntityList!=null && sysRoleEntityList.size()>0){
           for (SysRoleEntity sysRoleEntity: sysRoleEntityList){
               authorities.add(new SimpleGrantedAuthority("ROLE_" + sysRoleEntity.getRoleName()));
           }
           userInfo.setAuthorities(authorities);
       }
        // 进行登录
        return new UsernamePasswordAuthenticationToken(userInfo, password, authorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }



}
